package cn.xyinping.es;

import org.elasticsearch.action.delete.DeleteRequestBuilder;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequestBuilder;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 27266
 * @desrciption
 * @date 2021/11/13
 */
public class ESTest {
    // 连接ES
    public TransportClient getClient() throws UnknownHostException {
        // 设置
        Settings settings = Settings.builder()
                // 嗅探  当连接到这个ES主机后就会把其他的ES主机找出来
                .put("client.transport.sniff", true).build();
        // ES 客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                // 一个ES 主机
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        return client;
    }

    /**
     * 添加
     * @throws UnknownHostException
     */
    @Test
     public void addEs() throws UnknownHostException {
       for (int i=1; i<=100; i++){
           // 连接ES
           TransportClient client = getClient();
           // 创建索引库
           IndexRequestBuilder builder = client.prepareIndex("pethome", "user", i+"");
           // 添加
           HashMap<String, Object> map = new HashMap<>();
           map.put("id", 1);
           map.put("username",i%2==0?"吉泽老师":"优雅老师");
           map.put("age", i%3==0?"1":"0");
           map.put("sex", 1);
           IndexResponse indexResponse = builder.setSource(map).get();
           System.out.println(indexResponse);
       }
    }

    /**
     * 获取
     * @throws UnknownHostException
     */
    @Test
     public void getES() throws UnknownHostException {
        // 连接ES
        TransportClient client = getClient();
        // 获取
        GetRequestBuilder getRequestBuilder = client.prepareGet("pethome", "user", "1");
        // 获取结果
        GetResponse getFields = getRequestBuilder.get();
        System.out.println(getFields.getSource());
    }

    /**
     * 修改
     * @throws UnknownHostException
     */
    @Test
     public void updateES() throws UnknownHostException {
        // 连接ES
        TransportClient client = getClient();
        // 修改
        UpdateRequestBuilder updateRequestBuilder = client.prepareUpdate("pethome", "user", "1");
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", 1);
        map.put("username","优雅老师");
        map.put("age", 35);
        map.put("sex", 1);
        UpdateResponse updateResponse = updateRequestBuilder.setDoc(map).get();
        System.out.println(updateResponse);
    }

    /**
     * 删除
     * @throws UnknownHostException
     */
    @Test
     public void deleteES() throws UnknownHostException {
        // 连接ES
        TransportClient client = getClient();
        DeleteRequestBuilder deleteRequestBuilder = client.prepareDelete("pethome", "user", "1");
        DeleteResponse deleteResponse = deleteRequestBuilder.get();
        System.out.println(deleteResponse);
    }

    /**
     * 综合查询
     * 要求：username为 优雅老师，吉泽老师  年龄在20——50之间的
     * 按照age倒序排序 查询第一页每页十条
     */
    @Test
     public void search() throws UnknownHostException {
        // 连接ES
        TransportClient client = getClient();
        // 指定要搜索的索引库
        SearchRequestBuilder searchRequestBuilder = client.prepareSearch("pethome");
        // 排序   倒序
        searchRequestBuilder.addSort("age", SortOrder.DESC);
        // 分页
        searchRequestBuilder.setFrom(0);
        searchRequestBuilder.setSize(10);
        // 查询条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 根据username条件来查询
        boolQueryBuilder.must(QueryBuilders.matchQuery("username", "优雅老师 吉泽老师"));
        // 根据age sex来查询
        boolQueryBuilder
                .filter(QueryBuilders.termQuery("sex", 1))
                .filter(QueryBuilders.rangeQuery("age").gte(20).lte(50));
        // 获取结果
        SearchResponse searchResponse = searchRequestBuilder.setQuery(boolQueryBuilder).get();
        // 查询得到的结果
        SearchHits searchHits = searchResponse.getHits();
        // 获取查询到的总条数
        long totalHits = searchHits.getTotalHits();
        System.out.println("总条数:"+totalHits);
        // 查询结果列表
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            // 拿到数据
            Map<String, Object> source = hit.getSource();
            System.out.println(source);
        }
    }
}
